package com.yanqu.road.server.gameplayer.module.activity.rankunionwar;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.rankunionwar.config.RankUnionWarConfig;
import com.yanqu.road.entity.activity.rankunionwar.config.RankUnionWarDivisionConfig;
import com.yanqu.road.entity.activity.rankunionwar.config.RankUnionWarFloorConfig;
import com.yanqu.road.entity.activity.rankunionwar.config.RankUnionWarTimeConfig;
import com.yanqu.road.entity.activity.rankunionwar.data.RankUnionWarUserData;
import com.yanqu.road.entity.config.skill.SkillInfo;
import com.yanqu.road.entity.cricket.CricketData;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eShopType;
import com.yanqu.road.entity.enums.eSkillType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.manor.FishData;
import com.yanqu.road.entity.player.*;
import com.yanqu.road.logic.bussiness.activity.RankUnionWarBusiness;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.RankUnionWarProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.ActivityMallModule;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.cricket.CricketMgr;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.activity.rankunionwar.RankUnionWarMgr;
import com.yanqu.road.server.manger.config.PatronsMgr;
import com.yanqu.road.server.manger.config.SkillMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.config.VehicleMgr;
import com.yanqu.road.server.manger.manor.FishPondMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class RankUnionWarModule extends GeneralModule {

    private RankUnionWarUserData userData;

    public RankUnionWarModule(GamePlayer player) {
        super(player);
    }

    public RankUnionWarUserData getUserData(){
        return userData;
    }


    public void initUserData(int activityId){
        if(userData == null || userData.getActivityId() != activityId){
            RankUnionWarUserData tempUserData = new RankUnionWarUserData();
            tempUserData.setActivityId(activityId);
            tempUserData.setUserId(getUserId());
            tempUserData.setPassTimes(0);
            initNextBoxInfo(tempUserData);
            tempUserData.setInsertOption();
            userData = tempUserData;
        }
    }

    //初始化宝箱数据
    private void initNextBoxInfo(RankUnionWarUserData userData){
        Map<Integer, RankUnionWarFloorConfig> floorConfigMap = RankUnionWarMgr.getConfig().getFloorConfigMap();
        if(floorConfigMap.containsKey(userData.getFloor() + 1)){
            userData.setFloor(userData.getFloor() + 1);
        }else{
            userData.setFloor(1);
            userData.setPassTimes(userData.getPassTimes() + 1);
        }
        int bigRewardPos = RankUnionWarMgr.randomBigRewardPosition();
        userData.setBigRewardPosition(bigRewardPos);
        Map<Integer, String> openFloorMap = new ConcurrentHashMap<>();
        for(int i = 0 ; i < RankUnionWarMgr.getConfig().getBoxLength() ;i++){
            openFloorMap.put(i,"");
        }
        userData.setFloorOpenMap(openFloorMap);
    }

    //宝库信息
    public void boxInfo(){
        RankUnionWarProto.RankUnionWarBoxRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarBoxRespMsg.newBuilder();
        respMsg.setRet(0);
        Map<Integer, String> openMap = userData.getFloorOpenMap();
        if(openMap == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_BOX_NO_SENIORITY);
            player.sendPacket(Protocol.U_RANKUNIONWAR_BOX_INFO, respMsg);
            return;
        }
        respMsg.setFloor(userData.getFloor());
        for(int i = 0 ; i < RankUnionWarMgr.getConfig().getBoxLength() ;i++){
            RankUnionWarProto.RankUnionWarCellData.Builder cellMsg = RankUnionWarProto.RankUnionWarCellData.newBuilder();
            cellMsg.setOpen(false);
            if(!StringUtils.isNullOrEmpty(openMap.get(i))){
                cellMsg.setOpen(true);
                cellMsg.setReward(openMap.get(i));
            }
            respMsg.addCell(cellMsg);
        }
        respMsg.setGotBigReward(userData.getPassTimes() > 0?1:0);
        player.sendPacket(Protocol.U_RANKUNIONWAR_BOX_INFO, respMsg);
    }

    //宝库开启
    public int openBox(int floor,int id){
        //客户端从1开始的
        id = id - 1;
        RankUnionWarProto.RankUnionWarBoxOpenRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarBoxOpenRespMsg.newBuilder();
        respMsg.setRet(0);
        if(id < 0 || id > RankUnionWarMgr.getConfig().getBoxLength() - 1){
            return GameErrorCode.E_RANKUNIONWAR_BOX_OPEN_ERR;
        }
        if(floor != userData.getFloor()){
            return GameErrorCode.E_RANKUNIONWAR_BOX_OPEN_ERR;
        }
        Map<Integer, String> floorMap = userData.getFloorOpenMap();
        if(!StringUtils.isNullOrEmpty(floorMap.get(id))){
            return GameErrorCode.E_RANKUNIONWAR_BOX_POSITION_IS_OPEN;
        }
        String cost = RankUnionWarMgr.getFloorOpenCost(userData.getFloor());
        if(!player.getModule(CurrencyModule.class).currencyIsEnough(PropertyHelper.parseStringToProperty(cost))){
            return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
        }
        player.getModule(CurrencyModule.class).removeCurrency(PropertyHelper.parseStringToProperty(cost), eLogMoneyType.RankUnionWar,eLogMoneyType.RankUnionWarOpenBoxCost);
        if(id == userData.getBigRewardPosition()){
            String reward = RankUnionWarMgr.randomBoxBigReward(userData.getFloor());
            player.getModule(CurrencyModule.class).addCurrency(PropertyHelper.parseStringToProperty(reward), eLogMoneyType.RankUnionWar,eLogMoneyType.RankUnionWarOpenBoxBigReward);
            floorMap.put(id,reward);
            respMsg.setFloor(floor);
            respMsg.setReward(reward);
            respMsg.setSpecial(true);
            initNextBoxInfo(userData);
        }else{
            String reward = RankUnionWarMgr.randomBoxReward(userData.getFloor());
            player.getModule(CurrencyModule.class).addCurrency(PropertyHelper.parseStringToProperty(reward), eLogMoneyType.RankUnionWar,eLogMoneyType.RankUnionWarOpenBoxNormalReward);
            floorMap.put(id,reward);
            userData.setFloorOpenMap(floorMap);
            respMsg.setFloor(floor);
            respMsg.setReward(reward);
            respMsg.setSpecial(false);
        }
        player.sendPacket(Protocol.U_RANKUNIONWAR_BOX_OPEN, respMsg);
        return 0;
    }

    public void syncConfigData(){
        RankUnionWarConfig config = RankUnionWarMgr.getConfig();
        Map<Integer, RankUnionWarTimeConfig> timeConfigMap = config.getTimeConfigMap();
        Map<Integer, RankUnionWarDivisionConfig> divisionConfigMap = config.getDivisionConfigMap();
        Map<Integer, RankUnionWarFloorConfig> floorConfigMap = config.getFloorConfigMap();
        RankUnionWarProto.RankUnionWarConfigDataSyncMsg.Builder configMsg = RankUnionWarProto.RankUnionWarConfigDataSyncMsg.newBuilder();
        configMsg.setActivityId(config.getActivityInfo().getActivityId());
        RankUnionWarProto.RankUnionWarConfigDataTemp.Builder configDataMsg = RankUnionWarProto.RankUnionWarConfigDataTemp.newBuilder();
        for(RankUnionWarTimeConfig timeConfig : timeConfigMap.values()){
            RankUnionWarProto.PeakUnionTimeTemp.Builder timeMsg = RankUnionWarProto.PeakUnionTimeTemp.newBuilder();
            timeMsg.setTimeId(timeConfig.getTimeId());
            timeMsg.setSession(timeConfig.getSession());
            timeMsg.setBeginTime(timeConfig.getBeginTime());
            timeMsg.setDurTime(timeConfig.getDurTime());
            configDataMsg.addTimes(timeMsg);
        }
        for(RankUnionWarDivisionConfig divisionConfig : divisionConfigMap.values()){
            RankUnionWarProto.PeakUnionDivisionTemp.Builder divisionMsg = RankUnionWarProto.PeakUnionDivisionTemp.newBuilder();
            divisionMsg.setDivision(divisionConfig.getDivision());
            divisionMsg.setScore(divisionConfig.getScore());
            divisionMsg.setRewardsPresident(divisionConfig.getRewardsPresident());
            divisionMsg.setRewardsMember(divisionConfig.getRewardsMember());
            configDataMsg.addDivisions(divisionMsg);
        }
        for(RankUnionWarFloorConfig floorConfig : floorConfigMap.values()){
            RankUnionWarProto.PeakUnionFloorTemp.Builder floorMsg = RankUnionWarProto.PeakUnionFloorTemp.newBuilder();
            floorMsg.setFloor(floorConfig.getFloor());
            floorMsg.setSpecialReward(floorConfig.getSpecialRewardAll());
            floorMsg.setRewards(floorConfig.getRewards());
            floorMsg.setConsume(floorConfig.getConsume());
            configDataMsg.addFloors(floorMsg);
        }
        configMsg.setConfigData(configDataMsg);
        player.sendPacket(Protocol.U_RANKUNIONWAR_CONFIG_SYNC, configMsg);
    }

    public void syncUserData(){
        RankUnionWarProto.CrossRankUnionWarUserDataSyncMsg.Builder syncMsg = RankUnionWarProto.CrossRankUnionWarUserDataSyncMsg.newBuilder();
        syncMsg.setActivityId(RankUnionWarMgr.getConfig().getActivityInfo().getActivityId());
        syncMsg.setPatronsSkillAdd(getDispatchPatronsAddition());
        player.sendPacket(CrossProtocol.C2_CROSS_RANKUNIONWAR_USER_INFO_SYNC, syncMsg);
    }

    public void syncLoginConditionData(){
        RankUnionWarProto.CrossRankUnionWarUserDataSyncMsg.Builder syncMsg = RankUnionWarProto.CrossRankUnionWarUserDataSyncMsg.newBuilder();
        syncMsg.setActivityId(RankUnionWarMgr.getConfig().getActivityInfo().getActivityId());
        UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(getUserId(), GameServer.getInstance().getServerId());
        if(userBaseInfo != null){
            syncMsg.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
        }
        player.sendPacket(CrossProtocol.C2_CROSS_RANKUNIONWAR_SYNC_LOGIN_CONDITION, syncMsg);
    }


    //同步门客信息，招募的时候同步一下
    public void syncUserPatronsData(int activityId,List<Integer> patronsIdList){
        RankUnionWarProto.CrossRankUnionWarGetPatronsRespMsg.Builder respMsg = RankUnionWarProto.CrossRankUnionWarGetPatronsRespMsg.newBuilder();
        respMsg.setActivityId(activityId);
        RankUnionWarProto.CrossRankUnionWarPatronsUpdateMsg.Builder userMsg = RankUnionWarProto.CrossRankUnionWarPatronsUpdateMsg.newBuilder();
        UserInfo userInfo = UserMgr.getUserInfo(player.getUserId());
        userMsg.setUnionUid(userInfo == null?"":userInfo.getUnionUid());
        userMsg.setUserId(player.getUserId());
        for(int patronsId : patronsIdList){
            UserPatrons userPatrons = player.getModule(PatronsModule.class).getUserPatrons(patronsId);
            RankUnionWarProto.CrossRankUnionWarPatronsMsg.Builder patronsMsg = RankUnionWarProto.CrossRankUnionWarPatronsMsg.newBuilder();
            patronsMsg.setPatronsId(userPatrons.getPatronsId());
            patronsMsg.setEarnSpeed(userPatrons.getAbility().toString());
            patronsMsg.setSkinId(userPatrons.getSkinId());
            patronsMsg.setPromotionId(userPatrons.getShowPromotionId());
            userMsg.addPatrons(patronsMsg);
        }
        respMsg.addUsers(userMsg);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_CROSS_RANKUNIONWAR_SET_PATRONS_INFO, respMsg);
        GamePlayerMgr.sendPacket(player.getUserId(), pbMsg);
    }


    //领取每一轮的观战奖励
    public int getLookReward(int turn, String reward) {
        List<Integer> lookRewardList = userData.getLookRewardMapList();
        if(lookRewardList.contains(turn)){
            return GameErrorCode.E_RANKUNIONWAR_IS_GET_LOOK_REWARD;
        }
        lookRewardList.add(turn);
        userData.setLookRewardMapList(lookRewardList);
        player.getModule(CurrencyModule.class).addCurrency(reward,eLogMoneyType.RankUnionWar,eLogMoneyType.RankUnionWarInspireReward);
        return  0;
    }

    public boolean isGetLookReward(int turn) {
        List<Integer> lookRewardList = userData.getLookRewardMapList();
        if(lookRewardList.contains(turn)){
            return true;
        }
        return false;
    }

    /**
     * 系统解锁
     */
    public void initSystem() {
        if(RankUnionWarMgr.getConfig() != null){
            ActivityInfo activityInfo = RankUnionWarMgr.getConfig().getActivityInfo();
            if(activityInfo != null){
                initUserData(activityInfo.getActivityId());
                syncConfigData();
                syncUserData();
                resetMall();
            }
        }
    }

    public void resetMall(){
        RankUnionWarConfig config = RankUnionWarMgr.getConfig();
        if(config != null){
            long resetTime = 0;
            RankUnionWarTimeConfig nowTimeConfig = config.getTimeConfig(System.currentTimeMillis());
            if(nowTimeConfig != null){
                if(nowTimeConfig.getSession() == 1){
                    resetTime = config.getActivityInfo().getBeginTime();
                }else{
                    RankUnionWarTimeConfig lastTimeConfig = config.getTimeConfig(nowTimeConfig.getSession() - 1);
                    resetTime = lastTimeConfig.getEndTime()/1000;
                }
                //随便找个时间点来重置，找不到开始时间，就用结束时间
                player.getModule(ActivityMallModule.class).resetCustomMall(eShopType.RankUnionWarYuanBaoMall.getValue(),resetTime);
                player.getModule(ActivityMallModule.class).resetCustomMall(eShopType.RankUnionWarRmbMall.getValue(),resetTime);
            }
        }
    }

    //装备了珍兽了直接上 门客装备了什么
    public void equipVehicleOrFish(int patronsId) {
        RankUnionWarProto.CrossRankUnionWarGetPatronsRespMsg.Builder respMsg = RankUnionWarProto.CrossRankUnionWarGetPatronsRespMsg.newBuilder();
        respMsg.setActivityId(RankUnionWarMgr.getActivityId());
        int turn = RankUnionWarMgr.getReadyTurn();
        if(turn == 0){
            return;
        }
        respMsg.setTurn(turn);
        UserInfo userInfo = UserMgr.getUserInfo(player.getUserId());
        if(userInfo == null || !RankUnionWarMgr.isMatchUnion(userInfo.getUnionUid())){
            return;
        }
        RankUnionWarProto.CrossRankUnionWarPatronsUpdateMsg.Builder userMsg = RankUnionWarProto.CrossRankUnionWarPatronsUpdateMsg.newBuilder();
        userMsg.setUserId(player.getUserId());
        //已经等了过了，商会信息肯定是稳的
        userMsg.setUnionUid(userInfo.getUnionUid());

        Map<Integer, UserPatrons> userPatronsMap = PatronsMgr.getUserPatronsMap(player.getUserId());
        Map<String, UserVehicle> userVehicleMap = VehicleMgr.getUserVehicleMap(player.getUserId());
        Map<Integer, FishData> userFishMap = FishPondMgr.getUserFishMap(player.getUserId());
        Map<Integer, CricketData> userCricketMap = CricketMgr.getUserCricketMap(player.getUserId());
        UserPatrons userPatrons = userPatronsMap.get(patronsId);
        RankUnionWarProto.CrossRankUnionWarPatronsMsg.Builder patronsMsg = RankUnionWarProto.CrossRankUnionWarPatronsMsg.newBuilder();
        patronsMsg.setPatronsId(userPatrons.getPatronsId());
        patronsMsg.setEarnSpeed(userPatrons.getAbility().toString());
        patronsMsg.setSkinId(userPatrons.getSkinId());
        patronsMsg.setPromotionId(userPatrons.getShowPromotionId());
        UserVehicle userVehicle = RankUnionWarMgr.getUserVehicle(userVehicleMap,userPatrons.getPatronsId());
        patronsMsg.setVehicleUid(userVehicle == null?"":userVehicle.getVehicleUid());
        FishData fishData = RankUnionWarMgr.getUserFish(userFishMap,userPatrons.getPatronsId());
        patronsMsg.setFishId(fishData == null?0:fishData.getFishId());
        CricketData cricketData = RankUnionWarMgr.getUserCricket(userCricketMap,userPatrons.getPatronsId());
        patronsMsg.setCricketId(cricketData == null?0:cricketData.getCricketId());
        userMsg.addPatrons(patronsMsg);
        respMsg.addUsers(userMsg);

        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_CROSS_RANKUNIONWAR_SET_PATRONS_INFO, respMsg);
        GamePlayerMgr.sendPacket(0, pbMsg);
    }

    @Override
    public boolean loadData() {
        if(SystemOpenMgr.systemOpen(player, eSystemId.RankUnionWar.getValue())){
            RankUnionWarConfig config = RankUnionWarMgr.getConfig();
            if(config != null){
                ActivityInfo activityInfo = config.getActivityInfo();
                if(activityInfo != null){
                    userData = RankUnionWarBusiness.getUserData(getUserId(),activityInfo.getActivityId());
                    if(userData == null){
                        initUserData(activityInfo.getActivityId());
                    }
                }
            }
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return false;
    }

    @Override
    public boolean saveData() {
        if(userData != null){
            if(userData.isInsertOption()){
                RankUnionWarBusiness.addUserData(userData);
            }else if(userData.isUpdateOption()){
                RankUnionWarBusiness.updateUserData(userData);
            }
        }
        return true;
    }

    @Override
    public void afterLogin() {
        if(SystemOpenMgr.systemOpen(player, eSystemId.RankUnionWar.getValue())){
            RankUnionWarConfig config = RankUnionWarMgr.getConfig();
            if(config != null){
                ActivityInfo activityInfo = RankUnionWarMgr.getConfig().getActivityInfo();
                if(activityInfo != null){
                    initUserData(activityInfo.getActivityId());
                    syncConfigData();
                    syncUserData();
                    syncLoginConditionData();
                    resetMall();
                }
            }
        }
    }



    /**
     * 派遣门客对所有门客加成
     */
    public int getDispatchPatronsAddition(){
        //策划说不会出现多个，出现多个用最大那个
        int maxAddition = 0;
        for(UserPatrons userPatrons : player.getModule(PatronsModule.class).getUserPatronsList()){
            for(UserPatronsSkill patronsSkill : userPatrons.getSkillList()){
                SkillInfo skillInfo = SkillMgr.getSkillInfo(patronsSkill.getSkillId());
                if(eSkillType.PatronsDispatchRankUnionWarAddition.getValue() == skillInfo.getType()){
                    int addition = SkillMgr.getSkillAddition(skillInfo, patronsSkill.getSkillLv());
                    if(maxAddition < addition){
                        maxAddition = addition;
                    }
                }
            }
        }
        return maxAddition;
    }

}
